<template>
  <div class="main clearfix">
    <index-head></index-head>
    <div class="breadcrumb_mainBody_tab_tilte">
      <index-breadcrumb></index-breadcrumb>
      <div class="listed_base_info_select">
        <el-select v-if=false v-model="baseApi" placeholder="请选择" @change="getList">
          <el-option v-for="item in baseApis" :key="item.key" :label="item.label" :value="item.key"></el-option>
        </el-select>
      </div>
      <div class="mainBody_tab_tilte_parent listed_tag_select">
        <ul class="mainBody_tab_tilte clearfix" style="color: #fff">
          <li @click="output">
            <img src="../assets/image/mainCon_icon2.png" />
            <span>导出数据</span>
          </li>
          <li @click="saveTableImg">
            <img src="../assets/image/mainCon_icon4.png" />
            <span>保存为图片</span>
          </li>
        </ul>
      </div>
    </div>
    <div class="mainPositionWin" v-show="mainPositionWinShow">
      <div class="positionTitle">
        <div class="clearfix">
          <p class="positionTitle_a">条件</p>
          <p class="positionTitle_close" @click="conditionsClose">
            <img src="../assets/image/close.png" />
          </p>
          <p class="positionTitle_clear" @click="conditionsClear">清空</p>
          <p class="positionTitle_extract" @click="termSubmit">数据提取</p>
        </div>
        <div class="navCntBox" style="margin-bottom: 20px">
          
          <div class="getIndexBox">
            <span class="titleYellow">行业</span>
            <!-- <input
              type="text"
              v-model="filterGetIndex"
              placeholder="输入关键字进行过滤"
              class="getIndexInput"
            /> -->
            <el-checkbox-group v-model="getHy" @change="handleCheckedGetHyChange">
              <el-checkbox v-show="
                  filterGetHy ? item.indexOf(filterGetHy) >= 0 : true
                " v-for="item in defaultCheckedKeysDataHy" :label="item" :key="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="getTimeBox">
            <p class="titleYellow">规模</p>
            <el-checkbox-group v-model="getScale" @change="handleCheckedGetScaleChange">
              <el-checkbox v-for="item in defaultCheckedKeysScale" :label="item" :key="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="getIndexBox">
            <span class="titleYellow">指标</span>
            <!-- <input
              type="text"
              v-model="filterGetIndex"
              placeholder="输入关键字进行过滤"
              class="getIndexInput"
            /> -->
            <el-checkbox-group v-model="getIndex" @change="handleCheckedGetIndexChange">
              <el-checkbox v-show="
                  filterGetIndex ? item.indexOf(filterGetIndex) >= 0 : true
                " v-for="item in defaultCheckedKeysData" :label="item" :key="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="getTimeBox" style="border-right: 1px solid #595a60">
            <p class="titleYellow">时间</p>
            <el-checkbox-group v-model="getTime" @change="handleCheckedGetTimeChange">
              <el-checkbox v-for="item in defaultCheckedKeysTime" :label="item" :key="item">{{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
        </div>
      </div>
    </div>
    <div class="clearfix">
      <div class="mainTerm">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="行业" name="first">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextHy" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextHyClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataHy" :props="defaultProps" check-strictly="false" :default-expand-all="false" :filter-node-method="filterNode" ref="treeHy" show-checkbox node-key="label" :default-expanded-keys="[]" :default-checked-keys="defaultCheckedKeysDataHy" @check="nodeClickHandleHy"></el-tree>
            </div>
            <!--            @check-change="checkChangeHandle"-->
          </el-tab-pane>
          <el-tab-pane label="规模" name="baseInfo" class="timeCheck">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextScale" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextScale = ''" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataHsplate" node-key="label" :props="defaultProps" :default-expand-all="true" :filter-node-method="filterNode" ref="dataHsplate" show-checkbox :default-checked-keys="defaultCheckedKeysScale" @check="nodeClickHandleScale"></el-tree>
              <!--              @check-change="checkChangeHandleRegion"-->
            </div>
          </el-tab-pane>
          <el-tab-pane label="指标" name="four">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterText" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="data" :props="defaultProps" :filter-node-method="filterNode" ref="tree" show-checkbox node-key="label" :default-expanded-keys="[]" :default-checked-keys="defaultCheckedKeysData" @check="nodeClickHandle"></el-tree>
            </div>
            <!--            @check-change="checkChangeHandle"-->
          </el-tab-pane>

          
          <el-tab-pane label="时间" name="three" class="timeCheck">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextTime" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextTimeClear" />
            </div>

            <el-dropdown trigger="click" @command="timeFilterSelectFn" style="color: #fff" class="timeSelect">
              <span class="el-dropdown-link">
                {{ timeFilterSelectVal
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="item" v-for="item in timeFilterSelectArr" :key="item.label">{{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <div class="tree">
              <el-tree class="filter-tree" :data="dataTime" :props="defaultProps" :default-expand-all="true" :filter-node-method="filterNode" ref="treeTime" show-checkbox node-key="label" :default-checked-keys="defaultCheckedKeysTime" @check="nodeClickHandleTime"></el-tree>
            </div>
          </el-tab-pane>
          
        </el-tabs>
        <p @click="termlook" class="conditions">查看条件</p>
      </div>
      <div class="mainContainer">
        <div class="table-l emptyLeft" ref="tableWrapper" v-loading="loading">
          <el-table id="mytable" :data="tableData" :default-sort="{prop: 'timeCode', order: 'descending'}" style="width: 100%" height="75vh" ref="multipleTable">
            <el-table-column label="序号" type="index" width="75" fixed></el-table-column>
            <template v-for="item in tableColumn">
              <el-table-column :key="item.key" :prop="item.prop" :label="item.label" :fixed="!!item.fixed" :show-overflow-tooltip="true" :render-header="renderHeader"  sortable align="center">
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="flex-center">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[20, 40, 60, 80]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- <detailsDialog ref="detailsDialog" /> -->
  </div>
</template>

<script>
import { mapGetters ,mapMutations} from 'vuex'
import indexBreadcrumb from "../components/breadcrumb";
import indexHead from "../components/head";
import XLSX from "xlsx";
import _ from 'lodash';
import FileSaver from "file-saver";
import html2canvas from "html2canvas";
import evaListPLageConfig from "./components/macro/evaListPageConfig";
// import detailsDialog from "./detailsDialog";
import { getHideAreaArr, tabTable } from "./components/macro/table.js";
export default {
  name: "evalist",
  components: {
    indexHead,
    indexBreadcrumb
  },
  data() {
    return {
      loading: false,
      baseApi: "1",
      baseApis: evaListPLageConfig,
      tableData: [],
      page: 1,
      limit: 20,
      total: 0,
      baseCodes: "",
      mainPositionWinShow: false,
      activeName: "first",
      filterText: "",
      filterTextHy: "",
      filterTextTime: "",
      filterTextScale: "",
      data: [],
      dataHy: [],
      defaultCheckedKeysData: [],
      defaultCheckedKeysDataHy: [],
      defaultCheckedKeysDataCodes: [],
      defaultCheckedKeysTime: [],
      // defaultCheckedKeysRegion: [],
      defaultCheckedKeysScale: [],
      getIndex: [],
      sourceDataChecked: [], // 接口返回的默认选中的指标
      filterGetIndex: "",
      filterGetHy: "",
      // getTimes: [],
      // getRegions: [],
      // getIndexs: [],
      getTime: [],
      getHy: [],
      getRegion: [],
      getScale: [],
      dataTime: [],
      dataHsplate: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      timeFilterSelectArr: [

        {
          value: 5,
          label: "近5年",
        },
        {
          value: 10,
          label: "近10年",
        },
        {
          value: 20,
          label: "近20年",
        },
      ],
      timeFilterSelectVal: "",
      sourceData: [],
      currentCode: "",
    };
  },
  // CODES
  computed: {
    ...mapGetters({ userInfo: 'getUserInfo' }),
    breadcrumb(){
      return this.$route.query.breadcrumb;
    },
    headTag(){
      return this.$route.query.headTag;
    },
    tableName() {
      if (this.$route.query.tablename.indexOf("season") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [

          {
            value: 4,
            label: "前4季度",
          },
          {
            value: 8,
            label: "前8季度",
          },
          {
            value: 12,
            label: "前12季度",
          },
        ];
      else if (this.$route.query.tablename.indexOf("month") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [

          {
            value: 12,
            label: "前12月",
          },
          {
            value: 24,
            label: "前24月",
          },
          {
            value: 36,
            label: "前36月",
          },
        ];

      return this.$route.query.tablename || "eva_df_year";
    },
    bodyInitData(){
      let item = this.baseApis.find((item) => {
        return item.key === this.baseApi;
      });va
      return {
        url: `5700/websingletable/getEvaData`,
        method: "post",
        params: {
          page: this.page,
          limit: this.limit,
          // codes: item.key === "1" ? "" : this.baseCodes,
          codes: this.defaultCheckedKeysData.join(","),
          hyCodes: this.defaultCheckedKeysDataHy.join(","),
          scale: this.defaultCheckedKeysScale.join(","),
          times: this.defaultCheckedKeysTime.join(","),
        },
      };
    },
    tableColumn() {
      return this.baseApis.find((item) => {
        return item.key === this.baseApi;
      }).thead;
    },
    bodyData() {
      let item = this.baseApis.find((item) => {
        return item.key === this.baseApi;
      });
      return {
        url: `5700/websingletable/findEvaData`,
        method: "get",
        params: {
          page: this.page,
          limit: this.limit,
          // codes: item.key === "1" ? "" : this.baseCodes,
          codes: this.defaultCheckedKeysData.join(","),
          hyCodes: this.defaultCheckedKeysDataHy.join(","),
          scale: this.defaultCheckedKeysScale.join(","),
          times: this.defaultCheckedKeysTime.join(","),
          tableName: this.tableName,
          type: this.type,
        },
      };
    }
  },
  inject: ["reload"],
  watch: {
    baseApis(v) {
      console.log(v)
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterTextHy(val) {
      this.$refs.treeHy.filter(val);
    },
    filterTextTime(val) {
      this.$refs.treeTime.filter(val);
    },
    filterTextScale(val) {
      this.$refs.dataHsplate.filter(val);
    },
    $route(to, from) {
      // 防止外部跳入重复执行
      if (to.name === from.name) this.reload();
    },
    defaultCheckedKeysData(val) {
      
      this.getIndex = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getIndex;
      emp.remove("全选");
    
    },
    defaultCheckedKeysDataHy(val) {
      this.getHy = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getHy;
      emp.remove("全选");
    },

    defaultCheckedKeysTime(val) {
      this.getTime = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getTime;
      emp.remove("全选");
    },
    defaultCheckedKeysScale(val) {
      this.getScale = val;
      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i;
        }
        return -1;
      };
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      var emp = this.getScale;
      emp.remove("全选");
    },
  },
  methods: {
    ...mapMutations(['setBreadcrumb','setHeadTag']),
    renderHeader(h, { column, $index }) {
        // 新建一个 span
        let span = document.createElement('span');
        // 设置表头名称
        span.innerText = column.label;
        // 临时插入 document
        document.body.appendChild(span);
        // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
        column.minWidth = span.getBoundingClientRect().width + 60;
        // 移除 document 中临时的 span
        document.body.removeChild(span);
        return h('span', column.label);
    },
   
      
    timeFilterSelectFn(val) {
      //  筛选年份

      this.timeFilterSelectVal = val.label;

      this.$refs.treeTime.setCheckedKeys(this.timeSource.slice(0, val.value));
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label ? data.label.indexOf(value) !== -1 : false;
    },
    nodeClickHandle(data, { checkedKeys, checkedNodes }) {
      this.defaultCheckedKeysData = checkedKeys;
      this.mainPositionWinShow = true;
    },
    nodeClickHandleHy(data, { checkedKeys, checkedNodes }) {
      this.dataHy
      this.defaultCheckedKeysDataHy = checkedKeys;
      this.mainPositionWinShow = true;
    },
    nodeClickHandleScale(data, { checkedKeys, checkedNodes }) {
      this.defaultCheckedKeysScale = checkedKeys;
      this.mainPositionWinShow = true;
    },
    nodeClickHandleTime(data, { checkedKeys, checkedNodes }) {
      this.defaultCheckedKeysTime = checkedKeys;
      this.mainPositionWinShow = true;
    },

    handleCheckedGetIndexChange() {
      this.defaultCheckedKeysData = this.getIndex;
      this.$refs.tree.setCheckedKeys(this.getIndex);
    },
    handleCheckedGetHyChange() {
      this.defaultCheckedKeysDataHy = this.getHy;
      this.$refs.treeHy.setCheckedKeys(this.getHy);
    },
    handleCheckedGetTimeChange() {
      this.defaultCheckedKeysTime = this.getTime;
      this.$refs.treeTime.setCheckedKeys(this.getTime);
    },
    handleCheckedGetScaleChange() {
      this.defaultCheckedKeysScale = this.getScale;
      this.$refs.dataHs.setCheckedKeys(this.getScale);
    },
    termSubmit() {
      // 提取数据
      this.getList(2).then(() => {
        this.mainPositionWinShow = false;
      });
    },
    conditionsClear() {
      this.defaultCheckedKeysData = [];
      this.defaultCheckedKeysDataHy = [];
      this.defaultCheckedKeysTime = [];
      this.defaultCheckedKeysScale = [];
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.treeHy.setCheckedKeys([]);
      this.$refs.treeTime.setCheckedKeys([]);
      this.$refs.dataHsplate.setCheckedKeys([]);
    },
    conditionsClose() {
      this.mainPositionWinShow = false;
      if (!this.getIndex.length) {
        this.getIndex = this.sourceDataChecked;
        this.handleCheckedGetIndexChange();
      }
    },
    filterTextClear() {
      this.filterText = "";
    },
    filterTextHyClear() {
      this.filterTextHyClear = "";
    },
    filterTextTimeClear() {
      this.filterTextTime = "";
    },
    termlook() {
      window.scrollTo(0, 0);
      this.mainPositionWinShow = true;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getList(this.type);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getList(this.type);
    },

    async getList(type) {
      this.type = type;
      var that = this;
     
      if(that.breadcrumb!=undefined){
        this.setBreadcrumb(that.breadcrumb.split(","))
      }
      if(that.headTag!=undefined){
        this.setHeadTag(that.headTag.split(","))
      }
      let res = await this.$axios.request(this.bodyData);
      if (String(res.data.code) === "1") {
        // 失败
        this.$message.error(res.data.resp_msg);
        return;
      }
      let datas = Object.assign([], _.get(res, "data.data", []));
      this.sourceData = _.cloneDeep(datas);
      this.tableData = Object.assign([], datas);
      console.log(this.tableData)
      this.total = _.get(res, "data.count", 0);
      this.$nextTick(() => {
        if (this.$refs.multipleTable && this.$refs.multipleTable.doLayout) {
          this.$refs.multipleTable.doLayout();
        }
      })
      if (this.baseApi === "1") {
        this.baseCodes = datas
          .map((item) => {
            return item.code;
          })
          .join(",");
      }
    },
    async getInfoList() {
      var that = this;
     
      if(that.breadcrumb!=undefined){
        this.setBreadcrumb(that.breadcrumb.split(","))
      }
      if(that.headTag!=undefined){
        this.setHeadTag(that.headTag.split(","))
      }
      let res = await this.$axios.request(this.bodyInitData);
      if (String(res.data.code) === "1") {
        // 失败
        this.$message.error(res.data.resp_msg);
        return;
      }
      let datas = Object.assign([], _.get(res, "data.data", []));
      this.sourceData = _.cloneDeep(datas);
      this.tableData = Object.assign([], datas);
      this.total = _.get(res, "data.count", 0);
      this.$nextTick(() => {
        if (this.$refs.multipleTable && this.$refs.multipleTable.doLayout) {
          this.$refs.multipleTable.doLayout();
        }
      })
      if (this.baseApi === "1") {
        this.baseCodes = datas
          .map((item) => {
            return item.code;
          })
          .join(",");
      }
    },
    saveTableImg() {
      let isexport = this.userInfo.exporttype
      if (!isexport) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }
      html2canvas(this.$refs.tableWrapper).then((canvas) => {
        let dataURL = canvas.toDataURL("image/png");
        let link = document.createElement("a");
        link.href = canvas.toDataURL(); //下载链接
        link.setAttribute("download", $(".excelName").html());
        link.style.display = "none"; //a标签隐藏
        document.body.appendChild(link);
        link.click();
      });
    },
    output() {
      let { exporttype, username, exportRestrictions } = this.userInfo
      if (!exporttype) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }
      if (exportRestrictions) {
        // 查看权限下的导出条数
        this.$axios.request({
          url: "5100/user/exportRestrictions",
          method: "get",
          params: {
            exportNumber: 0,
            userName: username
          },
        }).then(res => {
          let Rpieces = res.data
          if (Rpieces == 0) {
            this.$message({
              message: '试用账号，导出已达上限！',
              type: 'warning',
              showClose: true,
              duration: 3000,
              center: true
            });
            return
          } else {
            // 拷贝原有数据
            let original = JSON.parse(JSON.stringify(this.tableData));
            if (this.tableData.length > Rpieces) {
              let extract = this.tableData.slice(0, Rpieces);
              let Controlcol = this.ReservedBar(extract)
              this.tableData = Controlcol
              this.$nextTick(() => {
                this.QuickPass()
                this.Exportsuccess(Rpieces, username)
              })
            } else {
              let Controlcol = this.ReservedBar(this.tableData)
              this.tableData = Controlcol
              this.$nextTick(() => {
                this.QuickPass()
                this.Exportsuccess(this.tableData.length, username)
              })
            }
            // 还原原有数据
            setTimeout(() => {
              this.tableData = original
            })
          }
        })
      } else {
        this.QuickPass()
      }
    },

    // 横向保留20条
    ReservedBar(arr) {
      let newArr = arr.map(obj => {
        let newObj = {}
        let count = 0
        for (let key in obj) {
          if (count < 22) {
            newObj[key] = obj[key];
            count++;
          }
        }
        return newObj
      })
      return newArr
    },

    // 快速导出
    QuickPass() {
      var excelName = $(".excelName").html();
      var addFooterHtml =
      '<tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"><td></td><td>数据来源：数据圈</td></tr><tr class="tableNone"><td></td><td>联系人：刘老师</td></tr><tr class="tableNone"><td></td><td>电&nbsp;&nbsp;话：18810308405</td></tr><tr class="tableNone"><td></td><td>E-mail：shicong.liu@shujuquan.com</td></tr>';
      $("#mytable")
        .find(".el-table__fixed-body-wrapper")
        .find("tbody")
        .append(addFooterHtml);
      var fix = document.querySelector(".el-table__fixed");
      var wb;
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#mytable").removeChild(fix)
        );
        document.querySelector("#mytable").appendChild(fix);
        $(".tableNone").remove();
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#mytable"));
      }
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      let date = new Date();
      date = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `` + excelName + `${date}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    // 导出成功
    Exportsuccess(value, user) {
      this.$axios.request({
        url: "/5100/user/exportRestrictions",
        method: "get",
        params: {
          exportNumber: value,
          userName: user
        },
      }).then(res => {
        return res.data
      })
    },

    async firstInit() {
      var that = this;
      let result = tabTable.find((item) => {
        return item.tableName.indexOf(this.tableName) >= 0;
      });
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      let data1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getIndex",
            method: "get",
            params: params,
          })
          .then(function (response) {
            // var data = that.getNavData(response.data);
            let defaultCheckedKeysData = [];
            let defaultCheckedKeysDataCodes = [];
            response.data.forEach((item) => {
              if (item.isShow) {
                defaultCheckedKeysData.push(item.name);
                defaultCheckedKeysDataCodes.push(item.code);
              }
            });
            that.defaultCheckedKeysData = defaultCheckedKeysData;
            that.defaultCheckedKeysDataCodes = defaultCheckedKeysDataCodes;
            that.sourceDataChecked = _.cloneDeep(defaultCheckedKeysData);
            var data = that.getNavData(_.cloneDeep(response.data));
            that.data = data
            resolve(response);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      let dataHy1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getHy",
            method: "get",
            params: params,
          })
          .then(function (response) {
            // var data = that.getNavData(response.data);
            let defaultCheckedKeysDataHy = [];
            let defaultCheckedKeysDataHyCodes = [];
            response.data.forEach((item) => {
              if (item.isShow) {
                defaultCheckedKeysDataHy.push(item.name);
                defaultCheckedKeysDataHyCodes.push(item.code);
              }
            });
            that.defaultCheckedKeysDataHy = defaultCheckedKeysDataHy;
            that.defaultCheckedKeysDataHyCodes = defaultCheckedKeysDataHyCodes;
            that.sourceDataChecked = _.cloneDeep(defaultCheckedKeysDataHy);
            var dataHy = that.getNavData(_.cloneDeep(response.data));
            that.dataHy = dataHy
            resolve(response);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      let dataTime1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getTime",
            method: "get",
            params: params,
          })
          .then(function (res) {
            resolve(res);
            // 原始数据
            res.data.sort(function (a, b) {
              return b - a;
            });
            that.timeSource = res.data;
            if (res.data) {
              that.setTimeTrees(res, result);
            }
            that.defaultCheckedKeysTime = res.data;
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      //
      let dataScale1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getScale",
            method: "get",
            params: params,
          })
          .then(function (res) {
            console.log(res)
            // that.setRegionTrees(res, result);
            if (res) {
              let gethsplateArr = [];
              for (let e of res.data.datas) {
                gethsplateArr.push({
                  id: e,
                  label: e,
                });
              }
              that.dataHsplate = [
                {
                  id: "all",
                  label: "全选",
                  children: gethsplateArr,
                },
              ];
              that.defaultCheckedKeysScale = res.data.datas
            }
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      
      data1
        .then(() => {
          return dataHy1;
        })
        .then(() => {
          return dataTime1;
        })
        .then(() => {
          return dataScale1;
        })
        .then(() => {
          let pageType = this.$route.query.pageType;
          if (pageType === "changeParam") {
            // 自带默认查询数据,从收藏列表页面过来
            let { indexCode, regionCode, timeCode } = JSON.parse(
              localStorage.getItem("macroCodes")
            );
            // index_code: this.getIndex.join(','),  // 隐藏指标代码，隐藏提交
            //   region_code: this.getRegion.join(','), // 隐藏地区代码，隐藏提交
            //   time_code: this.getTime.join(','),  // 隐藏时间代码，隐藏提交
            //  that.termlook();
            let {getIndex, getScale, getTime} = this.viewConditions();
            this.checkChangeHandle(null, null, null, indexCode.split(","));
            this.checkChangeHandleRegion(
              null,
              null,
              null,
              regionCode.split(",")
            );
            this.checkChangeHandleTime(null, null, null, timeCode.split(","));
            // todo  从缓存中拿数据
            return this.termSubmit();
          }
          return that.websingletableGetData();
        })
        .finally(() => {
          that.mainPositionWinShow = false;
        });
        this.getList(1);
    },
    websingletableGetData() {
      // 默认 查看条件
      // var that = this;
      // var params = new URLSearchParams();
      // params.append("tableName", that.tableName);
      // return new Promise((resolve, reject) => {
      //   this.$axios
      //     .request({
      //       url: "5700/websingletable/getEsgData",
      //       method: "post",
      //       params: params,
      //     })
      //     .then(function (res) {
      //       that.sourceData = res.data;
      //       that.defaultData = res.data; // 默认数值
      //       // that.init();
      //       // that.termlook();
      //       resolve(res);
      //     })
      //     .catch(function (error) {
      //       reject(error);
      //     });
      // });
    },
    // 设置 点击查看条件按钮 设置 数组
    viewConditions() {
      // let {defaultData} = this;
      let { sourceData } = this;
      let getIndex = [];
      let getRegion = [];
      let getTime = [];
      for (let key in sourceData) {
        getIndex.push(key.split("|")[0]);
        let item1 = sourceData[key];
        for (let key1 in item1) {
          let region = key1.split("|")[0];
          if (getRegion.indexOf(region) < 0) {
            getRegion.push(region);
          }
          let item2 = item1[key1];
          for (let key2 in item2) {
            if (getTime.indexOf(key2) < 0) {
              getTime.push(key2);
            }
          }
        }
      }
      return {
        getIndex,
        getRegion,
        getTime,
      };
    },
    setTimeTrees(res, result) {
      if (!result || result.time === "1") {
        let timeArr = [];
        for (let e of res.data) {
          timeArr.push({
            id: e,
            label: e,
          });
        }
        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      } else if (result.time === "2") {
        let map = new Map();
        let timeArr = [];
        for (let e of res.data) {
          let year = e.substring(0, 4);
          let value = map.get(year) || [];
          value.push({
            id: e,
            label: e,
          });
          map.set(year, value);
        }
        for (let e of map) {
          let key = e[0];
          let value = e[1];
          timeArr.push({
            id: "id_" + key,
            label: key,
            children: value,
          });
        }

        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      }
    },
    getNavData(list, parentId) {
      if (!parentId) {
        parentId = 0;
      }
      let result = [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].parenid == parentId) {
          list[i].label = list[i].name;
          list[i].children = this.getNavData(list, list[i].id);
          result.push(list[i]);
        }
      }
      return result;
    },
  },
  mounted() {
    this.firstInit();
  },
};
</script>

<style scoped>
.mainBody {
  color: #fff;
  background-color: #25262e;
}

/deep/ .table-l {
  position: relative;
}

/deep/ .el-table__body-wrapper {
  border-top: 0 !important;
}

/deep/ .el-table__fixed-body-wrapper tbody tr td:nth-child(3) {
  cursor: pointer;
}
/deep/ .el-table__body tbody tr td div {
  border-bottom: 1px solid transparent;
}

/* /deep/ .el-table__fixed-body-wrapper tbody tr td:nth-child(3) div {
  border-bottom: 1px solid #1ac5e4;
  width: 70px !important;
  margin: 0 auto;
  box-sizing: border-box;
} */

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #1f2027;
  z-index: 4;
}
.el-table__empty-text {
  text-align: left;
  width: 100%;
  margin-left: 8%;
}
/deep/ .el-table__empty-block {
  justify-content: left;
}
/deep/ .el-table__empty-text {
  padding-left: 400px;
}

</style>
